package muilty_thread.java_current_practice_and_kernel.cp7;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LogService {


    private final BlockingQueue<String> blockingQueue;
    private final LogService.LoggerThread thread;
    private int resavations;
    private boolean isShutdown;

    public LogService(PrintWriter writer) {
        this.blockingQueue = new LinkedBlockingQueue<>();
        this.thread = new LogService.LoggerThread(writer);
        this.isShutdown = false;
        this.resavations = 0;
    }

    public void start(){
        thread.start();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown) {
                throw new InterruptedException();
            }
            resavations++;
        }
        blockingQueue.put(msg);

    }


    public class LoggerThread extends Thread{
        PrintWriter writer;

        public LoggerThread(PrintWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {

            try{
                while (true) {
                    synchronized (LoggerThread.this) {
                        if (isShutdown && resavations == 0) {
                            break;
                        }
                    }
                    String take = blockingQueue.take();
                    synchronized (LoggerThread.this) {
                        --resavations;
                    }
                    writer.println(take);


                }


            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                writer.close();
            }


        }
    }
}
